package org.TorontoAndroid;

import org.TorontoAndroid.R;

import android.app.Activity;
import android.content.Context;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;

public class MediaPlayerDemo extends Activity {
	
	private Context defaultContext;
	private MediaPlayer mp = new MediaPlayer();
	private Button b1, b2, b3, b4;
	
	// 1. OnCreate() is called when the activity is first created.
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.relative);
        defaultContext = this.getBaseContext();
        
        // 2. initialize views (UI elements)
        b1 = (Button)this.findViewById(R.id.Button01);
        b2 = (Button)this.findViewById(R.id.Button02);
        b3 = (Button)this.findViewById(R.id.Button03);
        b4 = (Button)this.findViewById(R.id.Button04);
        
        // 3. attach listener to views
        b1.setOnClickListener(b1ClickListener); // start
        b2.setOnClickListener(b2ClickListener); // stop
        b3.setOnClickListener(b3ClickListener); // backward
        b4.setOnClickListener(b4ClickListener); // forward
        
        // some comment
        
	}

	// 4. play button clicked
	private OnClickListener b1ClickListener = new OnClickListener(){
		public void onClick(View v){
			if ( ! mp.isPlaying()) {
			
				mp = MediaPlayer.create(defaultContext,R.raw.website);
				mp.setLooping(true);
				mp.start();
				Toast.makeText(defaultContext, "Music Started", Toast.LENGTH_SHORT).show();
			}
		}
	};
	
	// 5. stop button clicked
	private OnClickListener b2ClickListener = new OnClickListener(){
		public void onClick(View v){
			mp.stop();
			mp.reset();
			Toast.makeText(defaultContext, "Music Stopped", Toast.LENGTH_SHORT).show();
		}
	};

	// 6. back button clicked
	private OnClickListener b3ClickListener = new OnClickListener(){
		public void onClick(View v){
			int currentPos;
			currentPos = mp.getCurrentPosition();
			if (currentPos >= 3000){
				mp.seekTo(currentPos - 3000);
			}
			else
			{
				mp.seekTo(0);
			}
			Toast.makeText(defaultContext, "Backward 3 sec", Toast.LENGTH_SHORT).show();
		}
	};
	
	// 7. forward button clicked
	private OnClickListener b4ClickListener = new OnClickListener(){
		public void onClick(View v){
			int currentPos;
			currentPos = mp.getCurrentPosition();
			if (currentPos <= mp.getDuration() - 3000)
			{
				mp.seekTo(currentPos + 3000);
			}
			else
			{
				mp.seekTo(0);
			}
			Toast.makeText(defaultContext, "Forward 3 sec", Toast.LENGTH_SHORT).show();
		}
	};
}